package com.chhuang.ewcrm.ctrl;

import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.application.LPKeyBoardApp;
import com.chhuang.ewcrm.bean.DeliveryBean;
import com.chhuang.ewcrm.bean.WeighTypeBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WCustomerDao;
import com.chhuang.ewcrm.dao.WLicensePlateDao;
import com.chhuang.ewcrm.dao.WWeighTempDao;
import com.chhuang.ewcrm.dao.WWorkModeDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.file.FileUtil;
import com.chhuang.ewcrm.string.StringUtil;
import com.chhuang.ewcrm.thread.*;
import com.chhuang.ewcrm.utils.*;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXRadioButton;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.util.*;

import static javafx.application.Platform.runLater;
/**
 * @author chhuang
 * @create 2020-09-30-9:02
 */
public class WeighController implements InitController {
    private final Logger logger = LoggerFactory.getLogger(WeighController.class);

    final ToggleGroup workModeToggleGroup = new ToggleGroup();
    final ToggleGroup weighModeToggleGroup = new ToggleGroup();
    final ToggleGroup printModeToggleGroup = new ToggleGroup();

    @FXML
    private JFXButton greenButton1;
    @FXML
    private JFXButton redButton1;
    @FXML
    private JFXButton greenButton2;
    @FXML
    private JFXButton redButton2;
    @FXML
    private Label infraredLabel1;
    @FXML
    private Label infraredLabel2;
    @FXML
    private Label weighLEDLabel;
    @FXML
    private JFXRadioButton manualModeRadio;
    @FXML
    private JFXRadioButton autoModeRadio;
    @FXML
    private JFXRadioButton twoWeighRadio;
    @FXML
    private JFXRadioButton oneWeighRadio;
    @FXML
    private JFXRadioButton printRadio;
    @FXML
    private JFXRadioButton unPrintRadio;
    @FXML
    private TableView<WWeighTemp> weighListTableView;

    @FXML
    private VBox weighVBox;

    @FXML
    private FlowPane warehouse1FlowPane;//过磅类别是 内部周转 时里显示 原仓库名称 选项
    @FXML
    private FlowPane customerFlowPane;//过磅类别不是 内部周转 时里显示 客户名称 选项
    @FXML
    private FlowPane goods1FlowPane;//过磅类别是 内部周转 时里显示 原物品名称 选项
    @FXML
    private FlowPane salesmanFlowPane;//过磅类别是 入库 或 出库 里显示 业务员 选项
    @FXML
    private FlowPane priceFlowPane;
    @FXML
    private FlowPane deductionMoneyFlowPane;
    @FXML
    private FlowPane amountFlowPane;
    @FXML
    private FlowPane isDeliveryFlowPane;


    @FXML
    private ComboBox<WLicensePlate> lprComboBox;
    @FXML
    private JFXButton lpKeyBoardJFXButton;
    private StringProperty lptext = new SimpleStringProperty();//车牌字符串
    @FXML
    private ComboBox<WeighTypeBean> weighTypeComboBox;
    @FXML
    private ComboBox<EWarehouse> warehouseComboBox;
    @FXML
    private ComboBox<EWarehouse> warehouse1ComboBox;
    @FXML
    private ComboBox<WCustomer> customerComboBox;
    @FXML
    private ComboBox<EGoods> goodsComboBox;
    @FXML
    private ComboBox<EGoods> goods1ComboBox;
    @FXML
    private TextField remarkTextField;
    @FXML
    private ComboBox<SysUser> salesmanComboBox;
    @FXML
    private ComboBox<SysUser> chargemanComboBox;
    @FXML
    private ComboBox<DeliveryBean> isDeliveryComboBox;
    @FXML
    private TextField grossWeightTextField;//毛重
    @FXML
    private TextField tareWeightTextField;//皮重
    @FXML
    private TextField impurityWeightTextField;//扣重
    @FXML
    private TextField netWeightTextField;//净重
    @FXML
    private TextField priceTextField;
    @FXML
    private TextField amountTextField;
    @FXML
    private TextField deductionMoneyTextField;
    @FXML
    private Label amountLabel;
    @FXML
    private JFXButton getWeighJFXButton;
    @FXML
    private JFXButton saveJFXButton;
    @FXML
    private JFXButton reflushJFXButton;
    @FXML
    private Label numberLabel;

    private boolean autoWeigh = false;
    private boolean autoPrint = true;

    private final NumberTextFilter numberTextFilter = new NumberTextFilter();

    private InitWeighCommThread weighCommThread;
    private InitCtrlCommThread ctrlCommThread;
    private InitCameraThread cameraThread;
    private InitLPRCameraThread lprCameraThread;

    private final WWorkModeDao wWorkModeDao = App.getSession().getMapper(WWorkModeDao.class);
    private final WLicensePlateDao wLicensePlateDao = App.getSession().getMapper(WLicensePlateDao.class);
    private final WCustomerDao wCustomerDao = App.getSession().getMapper(WCustomerDao.class);
    private final WWeighTempDao wWeighTempDao = App.getSession().getMapper(WWeighTempDao.class);

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //初始化表格
        initTable();

        //开启过磅仪表串口通讯
        weighCommThread = new InitWeighCommThread(weighLEDLabel);
        new Thread(weighCommThread).start();

        //开启过磅控制设置串口工作线程
        ctrlCommThread = new InitCtrlCommThread(greenButton1, redButton1, greenButton2, redButton2, infraredLabel1, infraredLabel2);
        new Thread(ctrlCommThread).start();

        //打开监控摄像头
        cameraThread = new InitCameraThread();
        new Thread(cameraThread).start();

        //打开车牌识别摄像头
        lprCameraThread = new InitLPRCameraThread(lprComboBox, ctrlCommThread);
        new Thread(lprCameraThread).start();

        //初始化工作模式
        initWorkMode();
        //初始化过磅类别
        initWeighType();
        //初始化车牌
        initLp();
        //初始化仓库
        initWarehouse();
        //初始化客户
        initCustomer();
        //初始化商品
        initGoods();
        //初始化业务员和负责人
        initMan();
        //是否是自提
        initIsDelivery();
        //初始化毛皮扣重
        initWeigh();
        //初始化价格扣款总价
        initPrice();
        //初始化按钮监听
        initButton();
    }

    /**
     * 初始化表格
     */
    private void initTable() {
        //初始化表格
        new Thread((new InitTableThread(weighListTableView, numberLabel))).start();
        //设置行 支持双击
        weighListTableView.setRowFactory(wWeighTempTableView -> {
            TableRow<WWeighTemp> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    WWeighTemp wWeighTemp = row.getItem();
                    if(wWeighTemp!=null) {
                        boolean isbreak = false;
                        for (WLicensePlate item : lprComboBox.getItems()) {
                            if (item.getWlpNumber().equals(wWeighTemp.getLicensePlate())) {
                                lprComboBox.getSelectionModel().select(item);
                                isbreak = true;
                                break;
                            }
                        }
                        if(!isbreak) lptext.setValue(wWeighTemp.getLicensePlate());
                    }
                }
            });
            return row;
        });
    }

    /**
     * 是否是自提
     */
    private void initIsDelivery() {
        List<DeliveryBean> list = new LinkedList<>();
        list.add(new DeliveryBean(false, "否"));//0
        list.add(new DeliveryBean(true, "是"));//1
        isDeliveryComboBox.getItems().addAll(list);
        isDeliveryComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(DeliveryBean deliveryBean) {
                return deliveryBean==null?null:deliveryBean.getTitle();
            }

            @Override
            public DeliveryBean fromString(String s) {
                return null;
            }
        });
        isDeliveryComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue)->{
            WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
            if(weighTypeBean!=null)weighTypeAndIsDelivery(newValue.isDelivery(), weighTypeBean.getWeighTypeId());
        });
        isDeliveryComboBox.getSelectionModel().select(0);//默认选中第一项
    }

    /**
     * 过磅类别与是否自提联动
     * @param delivery
     * @param weighTypeId
     */
    private void weighTypeAndIsDelivery(boolean delivery, int weighTypeId){
        if(delivery){//是自提
            switch (weighTypeId){//入库自提的不需要填写金额
                case 0://入库
                    priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                    deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                    amountFlowPane.setVisible(false); amountFlowPane.setManaged(false);
                    break;
                default://其它
                    priceFlowPane.setVisible(true); priceFlowPane.setManaged(true);
                    deductionMoneyFlowPane.setVisible(true); deductionMoneyFlowPane.setManaged(true);
                    amountFlowPane.setVisible(true); amountFlowPane.setManaged(true);
                    break;
            }
        }else {
            switch (weighTypeId){//出库不是自提的不需要填写金额
                case 1://出库
                    priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                    deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                    amountFlowPane.setVisible(false); amountFlowPane.setManaged(false);
                    break;
                default://其它
                    priceFlowPane.setVisible(true); priceFlowPane.setManaged(true);
                    deductionMoneyFlowPane.setVisible(true); deductionMoneyFlowPane.setManaged(true);
                    amountFlowPane.setVisible(true); amountFlowPane.setManaged(true);
                    break;
            }
        }
    }

    /**
     * 车牌选择框加载数据
     */
    private void loadLPRComboBox(){
        List<WLicensePlate> wLicensePlateList = wLicensePlateDao.query(null);
        if(wLicensePlateList!=null && !wLicensePlateList.isEmpty()){
            lprComboBox.getItems().addAll(wLicensePlateList);
            new AutoCompleteComboBoxListener<>(lprComboBox);
        }
    }

    /**
     * 初始化车牌
     */
    private void initLp() {
        loadLPRComboBox();

        //只能输入大写
        lprComboBox.getEditor().setTextFormatter(new TextFormatter<>(new UpCastTextFilter()));

        lprComboBox.setConverter(new StringConverter<>() {
            //把对象，设置显示值
            @Override
            public String toString(WLicensePlate wLicensePlate) {
                return wLicensePlate!=null?wLicensePlate.getWlpNumber():null;
            }

            //添加新值时，转对象
            @Override
            public WLicensePlate fromString(String s) {
                WLicensePlate wLicensePlate = null;
                logger.debug("车牌号fromString()："+s);
                if(StringUtils.isNotEmpty(s)){
                    wLicensePlate = new WLicensePlate();
                    wLicensePlate.setWlpNumber(s.toUpperCase());
                    List<WLicensePlate> wLicensePlates = wLicensePlateDao.query(wLicensePlate);
                    if(wLicensePlate!=null && !wLicensePlates.isEmpty()){
                        wLicensePlate = wLicensePlates.get(0);
                    }else {
                        wLicensePlate.setCreateTime(new Date());
                        wLicensePlateDao.insert(wLicensePlate);

                        new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                                Constants.loginUser.getUsername(),
                                Constants.loginUser.getFullname(),
                                "过磅时添加新车牌："+wLicensePlate.toString())).start();

//                        lprComboBox.getItems().add(wLicensePlate);//这个不管用
                        loadLPRComboBox();
                    }
                }
                return wLicensePlate;
            }
        });

        //监听车牌输入框是否有选择
        lprComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldLicensePlate, newLicensePlate) -> {
            if(newLicensePlate==null) return;//清空，不做处理

            WWeighTemp weighTemp = new WWeighTemp();
            weighTemp.setLicensePlate(newLicensePlate.getWlpNumber());
            weighTemp.setStatus(-1);
            List<WWeighTemp> weighTemps = wWeighTempDao.query(weighTemp);
            if(weighTemps!=null && !weighTemps.isEmpty()){//可能需要二次过磅的车辆，第二次过磅
                autoForm(weighTemps.get(0));
            }

            //是否要自动过磅
            if(autoWeigh){//自动过磅
                new Thread(new AutoWeighThread(weighLEDLabel, this)).start();
            }
        });

        //弹出键盘输入车牌
        lpKeyBoardJFXButton.setOnAction(event -> new LPKeyBoardApp(lptext).start(new Stage()));
        //监听 车牌字符串 修改
        lptext.addListener((observableValue, s, t1) -> {
            logger.debug("车牌号lptext.addListener："+t1);
            if(StringUtils.isNotEmpty(t1)) {
                lprComboBox.getSelectionModel().select(lprComboBox.getConverter().fromString(t1));
            }
        });
    }

    //是否获取联动选择器（物品名称）开关
    private boolean isAutoForm = false;

    /**
     * 自动填写表单
     * @param weighTemp
     */
    private void autoForm(WWeighTemp weighTemp){
        if(weighTemp==null || weighTemp.getStatus() > -1) return; //状态不需要二次过磅
        isAutoForm = true;

        //过磅类别
        for(WeighTypeBean item : weighTypeComboBox.getItems()){
            if(item.getWeighTypeId()-weighTemp.getWeighType()==0){
                weighTypeComboBox.getSelectionModel().select(item);
                break;
            }else {
                weighTypeComboBox.getSelectionModel().select(0);
            }
        }
        //仓库名称
        if(warehouseComboBox.getItems()!=null && !warehouseComboBox.getItems().isEmpty()) {
            if (StringUtils.isNotEmpty(weighTemp.getWarehouseId())) {
                for (EWarehouse item : warehouseComboBox.getItems()) {
                    if (weighTemp.getWarehouseId().equals(item.getWarehouseId())) {
                        warehouseComboBox.getSelectionModel().select(item);
                        break;
                    }
                }
            }else {
                warehouseComboBox.getSelectionModel().select(0);
            }
        }
        //物品名称
        getEGoods(weighTemp.getWeighType(), weighTemp.getWarehouseId(), weighTemp.getGoodsId());
        //负责人
        if(chargemanComboBox.getItems()!=null && !chargemanComboBox.getItems().isEmpty()){
            if(StringUtils.isNotEmpty(weighTemp.getChargemanId())){
                for(SysUser item: chargemanComboBox.getItems()){
                    if(weighTemp.getChargemanId().equals(item.getUserId())){
                        chargemanComboBox.getSelectionModel().select(item);
                        break;
                    }
                }
            }else {
                chargemanComboBox.getSelectionModel().select(0);
            }
        }

        if(weighTemp.getWeighType()<2) {//入库和出库
            //业务员
            if (salesmanComboBox.getItems() != null && !salesmanComboBox.getItems().isEmpty()) {
                if (StringUtils.isNotEmpty(weighTemp.getSalesmanId())) {
                    for (SysUser item : salesmanComboBox.getItems()) {
                        if (weighTemp.getSalesmanId().equals(item.getUserId())) {
                            salesmanComboBox.getSelectionModel().select(item);
                            break;
                        }
                    }
                } else {
                    salesmanComboBox.getSelectionModel().select(0);
                }
            }
            //是否自提
            if (weighTemp.getIsDelivery()) {
                isDeliveryComboBox.getSelectionModel().select(1);//是
            } else {
                isDeliveryComboBox.getSelectionModel().select(0);//否
            }
        }

        if(weighTemp.getWeighType()==2){//内部周转
            //原仓库名称
            if(warehouse1ComboBox.getItems()!=null && !warehouse1ComboBox.getItems().isEmpty()) {
                if (StringUtils.isNotEmpty(weighTemp.getWarehouse1Id())) {
                    for (EWarehouse item : warehouse1ComboBox.getItems()) {
                        if (weighTemp.getWarehouse1Id().equals(item.getWarehouseId())) {
                            warehouse1ComboBox.getSelectionModel().select(item);
                            break;
                        }
                    }
                }else {
                    warehouse1ComboBox.getSelectionModel().select(0);
                }
            }
            //原物品名称
            getEGoods1(weighTemp.getWarehouse1Id(), weighTemp.getGoods1Id());
        }else {//不是内部周转
            //客户名称
            if(customerComboBox.getItems()!=null && !customerComboBox.getItems().isEmpty()) {
                if (StringUtils.isNotEmpty(weighTemp.getCustomerId())) {
                    for (WCustomer item : customerComboBox.getItems()) {
                        if(weighTemp.getCustomerId().equals(item.getCustomerId())){
                            customerComboBox.getSelectionModel().select(item);
                            break;
                        }
                    }
                }else {
                    customerComboBox.setValue(null);
                }
            }
        }
        //毛重
        grossWeightTextField.setText(weighTemp.getGrossWeight()==null?null:weighTemp.getGrossWeight().toString());
        //扣重
        impurityWeightTextField.setText(weighTemp.getImpurityWeight()==null?null:weighTemp.getImpurityWeight().toString());

        if((weighTemp.getWeighType()==0 && !weighTemp.getIsDelivery()) || //入库 不是自提 需要写价格等
                (weighTemp.getWeighType()==1 && weighTemp.getIsDelivery()) || //出库 是自提 需要写价格等
                weighTemp.getWeighType()==2){ //内部周转 需要写价格等
            //价格
            priceTextField.setText(weighTemp.getPrice()==null?null:weighTemp.getPrice().toString());
            //扣款
            deductionMoneyTextField.setText(weighTemp.getDeductionMoney()==null?null:weighTemp.getDeductionMoney().toString());
        }

        if(weighTemp.getWeighType()==3){//其它过磅，过磅费
            amountTextField.setText(weighTemp.getAmount()==null?null:weighTemp.getAmount().toString());
        }

        //备注
        remarkTextField.setText(weighTemp.getRemark());

        isAutoForm = false;
    }

    /**
     * 初始化业务员和负责人
     */
    private void initMan() {
        SysUser voidUser = new SysUser();
        voidUser.setUsername("--请选择--");

        StringConverter<SysUser> converter = new StringConverter<>() {
            @Override
            public String toString(SysUser sysUser) {
                return sysUser==null?null:(sysUser.getFullname()==null?sysUser.getUsername():sysUser.getFullname());
            }

            @Override
            public SysUser fromString(String s) {
                return null;
            }
        };

        chargemanComboBox.setConverter(converter);
        chargemanComboBox.getItems().add(voidUser);
        AppRequest.getInstance().getService().getChargerMans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取负责人请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()->
                                chargemanComboBox.getItems().addAll(users)
                            );
                        }
                    }
                });
        chargemanComboBox.getSelectionModel().select(0);

        salesmanComboBox.setConverter(converter);
        salesmanComboBox.getItems().add(voidUser);
        AppRequest.getInstance().getService().getSalesmans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取业务员请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()->
                                salesmanComboBox.getItems().addAll(users)
                            );
                        }
                    }
                });
        salesmanComboBox.getSelectionModel().select(0);
    }

    /**
     * 初始化商品
     */
    private void initGoods() {
        StringConverter<EGoods> converter = new StringConverter<>() {
            @Override
            public String toString(EGoods eGoods) {
                return eGoods==null?null:eGoods.getGoodsName();
            }

            @Override
            public EGoods fromString(String s) {
                return null;
            }
        };

        goodsComboBox.setConverter(converter);

        goods1ComboBox.setConverter(converter);
    }

    /**
     * 加载客户选择
     */
    private void loadCustomer(){
        List<WCustomer> wCustomerList = wCustomerDao.query(null);
        if(wCustomerList!=null && !wCustomerList.isEmpty()){
            customerComboBox.getItems().addAll(wCustomerList);
            new AutoCompleteComboBoxListener<>(customerComboBox);//自动完成功能
        }
    }

    /**
     * 初始化客户
     */
    private void initCustomer() {
        loadCustomer();

        customerComboBox.getEditor().setTextFormatter(new TextFormatter<>(new LengthTextFilter(127)));
        customerComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(WCustomer wCustomer) {
                return wCustomer==null?null:wCustomer.getCustomerName();
            }

            @Override
            public WCustomer fromString(String s) {
                WCustomer wCustomer = null;
                if(StringUtils.isNotEmpty(s)){
                    wCustomer = new WCustomer();
                    wCustomer.setCustomerName(s);
                    List<WCustomer> wCustomers = wCustomerDao.query(wCustomer);
                    if(wCustomers!=null && !wCustomers.isEmpty()){
                        wCustomer = wCustomers.get(0);
                    }else {
                        Date now = new Date();
                        wCustomer.setModifyTime(now);
                        wCustomer.setCreateTime(now);
                        wCustomerDao.insert(wCustomer);

                        new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                                Constants.loginUser.getUsername(),
                                Constants.loginUser.getFullname(),
                                "过磅时添加新客户：" + wCustomer.toString())).start();

//                        customerComboBox.getItems().add(wCustomer);
                        loadCustomer();
                    }
                }
                return wCustomer;
            }
        });
    }

    /**
     * 初始化仓库
     */
    private void initWarehouse() {
//        EWarehouse warehouseTemp = new EWarehouse();
//        warehouseTemp.setWarehouseName("--请选择--");
//        warehouseComboBox.getItems().add(warehouseTemp);
//        warehouse1ComboBox.getItems().add(warehouseTemp);

        AppRequest.getInstance().getService().getWarehouses()
            .compose(ServiceRxSchedulers.compose())
            .subscribe(new ServiceSubscriber<>("获取所有仓库请求") {
                @Override
                protected void onHandleSuccess(List<EWarehouse> warehouses) {
                    if(warehouses!=null && !warehouses.isEmpty()) {
                        runLater(()->{
                            warehouse1ComboBox.getItems().addAll(warehouses);
                            warehouseComboBox.getItems().addAll(warehouses);

                            warehouseComboBox.getSelectionModel().select(0);
                            warehouse1ComboBox.getSelectionModel().select(0);
                        });
                    }
                }
            });

        StringConverter<EWarehouse> converter = new StringConverter<>() {
            @Override
            public String toString(EWarehouse eWarehouse) {
                return eWarehouse==null?null:eWarehouse.getWarehouseName();
            }

            @Override
            public EWarehouse fromString(String s) {
                return null;
            }
        };

        warehouseComboBox.setConverter(converter);
        warehouse1ComboBox.setConverter(converter);

        warehouseComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            if(!isAutoForm) {
                WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
                //修改物品
                getEGoods(weighTypeBean.getWeighTypeId(), newValue == null ? null : newValue.getWarehouseId(), null);
            }
        });

        warehouse1ComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            if(!isAutoForm) {
                //修改原物品
                getEGoods1(newValue == null ? null : newValue.getWarehouseId(), null);
            }
        });

//        warehouseComboBox.getSelectionModel().select(0);
//        warehouse1ComboBox.getSelectionModel().select(0);
    }

    private void getEGoods(int weightTypeId, String warehouseId, String goodsId){
        int typeId = 0;
        switch (weightTypeId){
            case 0,2:typeId=0;break;
            case 1:typeId=1;break;
            case 3:typeId=2;break;
        }
        //修改物品
        AppRequest.getInstance().getService().getGoods(typeId, warehouseId)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取物品名称请求") {
                    @Override
                    protected void onHandleSuccess(List<EGoods> goodsList) {
                        runLater(()->{
                            goodsComboBox.getItems().clear();
                            if(goodsList!=null && !goodsList.isEmpty()) {
                                goodsComboBox.getItems().addAll(goodsList);
                                goodsComboBox.getSelectionModel().select(0);
                                if(StringUtils.isNotEmpty(goodsId)){
                                    for(EGoods item: goodsComboBox.getItems()){
                                        if(goodsId.equals(item.getGoodsId())){
                                            goodsComboBox.getSelectionModel().select(item);
                                            break;
                                        }
                                    }
                                }
                            }
                        });
                    }
                });
//        goodsComboBox.getSelectionModel().select(0);
    }

    private void getEGoods1(String warehouseId1, String goodsId){
        //修改原物品
        AppRequest.getInstance().getService().getGoods(1, warehouseId1)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取原物品名称请求") {
                    @Override
                    protected void onHandleSuccess(List<EGoods> goodsList) {
                        runLater(()-> {
                            goods1ComboBox.getItems().clear();
                            if (goodsList != null && !goodsList.isEmpty()) {
                                goods1ComboBox.getItems().addAll(goodsList);
                                goods1ComboBox.getSelectionModel().select(0);
                                if(StringUtils.isNotEmpty(goodsId)){
                                    for(EGoods item: goods1ComboBox.getItems()){
                                        if(goodsId.equals(item.getGoodsId())){
                                            goods1ComboBox.getSelectionModel().select(item);
                                            break;
                                        }
                                    }
                                }
                            }
                        });
                    }
                });
//        goods1ComboBox.getSelectionModel().select(0);
    }

    /**
     * 初始化重量输入框
     */
    private void initWeigh(){
        //毛重
        grossWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        grossWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoWeigh();
        });
        //皮重
        tareWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        tareWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoWeigh();
        });
        //设置扣重只接收数字输入
        impurityWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        //修改扣重时
        impurityWeightTextField.focusedProperty().addListener((observable, oldValue, newValue)->{
            if(!newValue) {
                autoWeigh();
            }
        });
        //净重
        netWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        netWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoMoney();
        });
    }

    /**
     * 初始化价格 扣款 总金额
     */
    private void initPrice() {
        //设置价格只接收数字
        priceTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        //修改价格时
        priceTextField.focusedProperty().addListener((observable, oldValue, newValue)->{
            if(!newValue) {
                autoMoney();
            }
        });

        //设置价格只接收数字
        deductionMoneyTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        deductionMoneyTextField.focusedProperty().addListener((observableValue, aBoolean, t1) -> {
            if(!t1){
                autoMoney();
            }
        });

        //设置总价只接收数字
        amountTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
    }

    /**
     * 联动重量 当毛重，皮重， 扣重 修改后 调用
     */
    private void autoWeigh(){
        String tareWeightStr = tareWeightTextField.getText();
        String grossWeightStr = grossWeightTextField.getText();
        if(StringUtils.isNotEmpty(tareWeightStr) && StringUtil.isPositiveNumber(tareWeightStr) &&
                StringUtils.isNotEmpty(grossWeightStr) && StringUtil.isPositiveNumber(grossWeightStr)){
            double tareWeight = Double.parseDouble(tareWeightStr);
            double grossWeight = Double.parseDouble(grossWeightStr);

            //扣重
            double impurityWeight = 0;
            String impurityWeightStr = impurityWeightTextField.getText();
            if(StringUtils.isNotEmpty(impurityWeightStr) && StringUtil.isPositiveNumber(impurityWeightStr))
                impurityWeight = Double.parseDouble(impurityWeightStr);

            //净重
            double netWeight = grossWeight-tareWeight-impurityWeight;
            netWeightTextField.setText(String.format("%.3f",netWeight));
        }
    }

    /**
     * 联动金额  当净重，价格 扣款 修改后 调用
     */
    private void autoMoney(){
        String netWeightStr = netWeightTextField.getText();
        WeighTypeBean weighTypeBean = weighTypeComboBox.getValue();
        if(StringUtils.isNotEmpty(netWeightStr) && StringUtil.isPositiveNumber(netWeightStr)&&
                weighTypeBean.getWeighTypeId()!=3){
            double netWeight = Double.parseDouble(netWeightStr);
            //扣款
            double deductionMoney = 0;
            String deductionMoneyStr = deductionMoneyTextField.getText();
            if(StringUtils.isNotEmpty(deductionMoneyStr) && StringUtil.isPositiveNumber(deductionMoneyStr))
                deductionMoney = Double.parseDouble(deductionMoneyStr);

            //价格存在 计算总价
            double price =0;
            String priceStr = priceTextField.getText();
            if(StringUtils.isNotEmpty(priceStr) && StringUtil.isPositiveNumber(priceStr))
                price = Double.parseDouble(priceStr);
            amountTextField.setText(String.format("%.2f",netWeight*price-deductionMoney));
        }
    }

    /**
     * 初始化过磅类别
     */
    private void initWeighType() {
        //过磅类别
        weighTypeComboBox.getItems().addAll(Constants.WEIGH_TYPES);
        weighTypeComboBox.setConverter(new StringConverter<>() {
            //把对象，设置显示值
            @Override
            public String toString(WeighTypeBean weighTypeBean) {
                return weighTypeBean==null?null:weighTypeBean.getWeighTypeName();
            }
            //添加新值时，转对象
            @Override
            public WeighTypeBean fromString(String s) {return null;}
        });
        weighTypeComboBox.getSelectionModel().selectedItemProperty().addListener(
                (ObservableValue<? extends WeighTypeBean> observableValue, WeighTypeBean oldWtb, WeighTypeBean newWtb)-> {
                    DeliveryBean delivery = isDeliveryComboBox.getSelectionModel().getSelectedItem();
                    if(delivery!=null)weighTypeAndIsDelivery(delivery.isDelivery(), newWtb.getWeighTypeId());

                    if(newWtb.getWeighTypeId()<2){//入库 或 出库
                        salesmanFlowPane.setVisible(true); salesmanFlowPane.setManaged(true);
                        isDeliveryFlowPane.setVisible(true);isDeliveryFlowPane.setManaged(true);
                        if(!isAutoForm)isDeliveryComboBox.getSelectionModel().select(newWtb.getWeighTypeId());
                    }else {
                        salesmanFlowPane.setVisible(false); salesmanFlowPane.setManaged(false);
                        isDeliveryFlowPane.setVisible(false);isDeliveryFlowPane.setManaged(false);
                    }

                    if(newWtb.getWeighTypeId()==2){//内部周转
                        warehouse1FlowPane.setVisible(true); warehouse1FlowPane.setManaged(true);
                        customerFlowPane.setVisible(false); customerFlowPane.setManaged(false);
                        goods1FlowPane.setVisible(true); goods1FlowPane.setManaged(true);
                    }else {
                        warehouse1FlowPane.setVisible(false);  warehouse1FlowPane.setManaged(false);
                        customerFlowPane.setVisible(true); customerFlowPane.setManaged(true);
                        goods1FlowPane.setVisible(false); goods1FlowPane.setManaged(false);
                    }

                    if(newWtb.getWeighTypeId()==3){//其它过磅
                        priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                        deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                        amountLabel.setText("过磅费：");amountTextField.setEditable(true);
                        amountTextField.setStyle("");
                    }else {
                        amountLabel.setText("总 价 ：");amountTextField.setEditable(false);
                        amountTextField.setStyle("-fx-background-color: gainsboro;");
                    }

                    //修改物品
                    if(!isAutoForm) {//双击表单时不需要联动
                        EWarehouse warehouse = warehouseComboBox.getValue();
                        getEGoods(newWtb.getWeighTypeId(), warehouse == null ? null : warehouse.getWarehouseId(), null);
                    }
                }
        );
        weighTypeComboBox.getSelectionModel().select(0);//默认选中第一项
    }

    /**
     * 创建抓取图片保存的目录
     * @return path
     */
    private String createCapturePicDir(){
        String dir1 = DateUtil.date2String(new Date(), DateUtil.YYYYMMDD);
        String dir2 = UUID.randomUUID().toString();
        String path = MyPath.getCapturePicPath() + dir1 + File.separator + dir2 + File.separator;
        logger.debug("保存图片的目录："+path);
        FileUtil.makePath(path);
        return path;
    }

    /**
     * 初始化工作模式
     */
    private void initWorkMode() {
        WWorkMode wWorkMode = wWorkModeDao.queryById("001");
        //选择工作模式 0手动/1自动
        manualModeRadio.setToggleGroup(workModeToggleGroup);
        autoModeRadio.setToggleGroup(workModeToggleGroup);
        Integer wmodeAuto = wWorkMode.getWmodeAuto();
        if(wmodeAuto!=null) {
            autoWeigh = wmodeAuto==1;
            workModeToggleGroup.getToggles().get(wWorkMode.getWmodeAuto()).setSelected(true);
        }
        workModeToggleGroup.selectedToggleProperty().addListener(
                (ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) -> {
                    if (new_toggle != null) {
                        int value = Integer.parseInt(new_toggle.getUserData().toString());
                        autoWeigh = value==1;
                        wWorkMode.setWmodeAuto(value);
                        wWorkMode.setModifyTime(new Date());
                        wWorkModeDao.update(wWorkMode);

                        new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                                Constants.loginUser.getUsername(),
                                Constants.loginUser.getFullname(),
                                "修改过磅模式为："+(value==1?"自动":"手动"))).start();
                    }
                }
        );

        //选择工作模式 0一次过磅 、 1二次过磅
        oneWeighRadio.setToggleGroup(weighModeToggleGroup);
        twoWeighRadio.setToggleGroup(weighModeToggleGroup);
        weighModeToggleGroup.getToggles().get(wWorkMode.getWmodeWeigh()).setSelected(true);
        weighModeToggleGroup.selectedToggleProperty().addListener(
                (ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) -> {
                    if (new_toggle != null) {
                        int value = Integer.parseInt(new_toggle.getUserData().toString());
                        wWorkMode.setWmodeWeigh(value);
                        wWorkMode.setModifyTime(new Date());
                        wWorkModeDao.update(wWorkMode);

                        new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                                Constants.loginUser.getUsername(),
                                Constants.loginUser.getFullname(),
                                "修改过磅次数为："+(value==1?"二次过磅":"一次过磅"))).start();
                    }
                }
        );

        //选择工作模式 1打印磅单、 0不打印磅单
        unPrintRadio.setToggleGroup(printModeToggleGroup);
        printRadio.setToggleGroup(printModeToggleGroup);
        Integer wmodePrint = wWorkMode.getWmodePrint();
        if(wmodePrint!=null) {
            autoPrint = wmodePrint==1;
            printModeToggleGroup.getToggles().get(wmodePrint).setSelected(true);
        }
        printModeToggleGroup.selectedToggleProperty().addListener(
                (ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) -> {
                    if (new_toggle != null) {
                        int value = Integer.parseInt(new_toggle.getUserData().toString());
                        autoPrint = value==1;
                        wWorkMode.setWmodePrint(value);
                        wWorkMode.setModifyTime(new Date());
                        wWorkModeDao.update(wWorkMode);
                        new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                                Constants.loginUser.getUsername(),
                                Constants.loginUser.getFullname(),
                                "修改打印模式为："+(value==1?"打印磅单":"不打印磅单"))).start();
                    }
                }
        );
    }


    private String capturePicDir = null;

    /**
     * 初始化按钮监听
     */
    private void initButton() {

        //点击获取过磅重量
        getWeighJFXButton.setOnAction(event -> getWeigh());

        //点击保存按钮
        saveJFXButton.setOnAction(event -> submitData());

        //刷新列表
        reflushJFXButton.setOnAction(event -> {
            clearForm();//清空表单
            reflushWeighListTableView();
        });
    }

    /**
     * 刷新列表
     */
    private void reflushWeighListTableView() {
        WWeighTemp wWeighTemp = new WWeighTemp();
        wWeighTemp.setStatus(-1);//-1表示需要二次过磅的数据
        List<WWeighTemp> wWeighTemps = wWeighTempDao.query(wWeighTemp);
        weighListTableView.getItems().clear();
        if(wWeighTemps!=null && !wWeighTemps.isEmpty()) {
            weighListTableView.getItems().addAll(wWeighTemps);
            numberLabel.setText(String.valueOf(wWeighTemps.size()));
        }else{
            numberLabel.setText("0");
        }
    }

    /**
     * 保存，提交数据
     */
    private void submitData() {
        if(Constants.loginUser==null) return;//没有登录

        WWeighTemp weighTemp = new WWeighTemp();
        weighTemp.setWeighmanId(Constants.loginUser.getUserId());
        weighTemp.setWeighmanName(Constants.loginUser.getFullname()==null?Constants.loginUser.getUsername():Constants.loginUser.getFullname());

        WLicensePlate licensePlate = lprComboBox.getValue();
        if(licensePlate==null || StringUtils.isEmpty(licensePlate.getWlpNumber())) {
            MyAlert.showError("错误","保存出错","请输入车牌号");
            return;
        }
        weighTemp.setLicensePlate(licensePlate.getWlpNumber());//车牌号

        String grossWeightStr = grossWeightTextField.getText();
        if(StringUtils.isEmpty(grossWeightStr) || !StringUtil.isPositiveNumber(grossWeightStr)){
            MyAlert.showError("错误","保存出错","请获取毛重");
            return;
        }
        weighTemp.setGrossWeight(Double.parseDouble(grossWeightStr));

        String tareWeightStr = tareWeightTextField.getText();
        if(StringUtils.isNotEmpty(tareWeightStr) && StringUtil.isPositiveNumber(tareWeightStr))
            weighTemp.setTareWeight(Double.parseDouble(tareWeightStr));

        String impurityWeightStr = impurityWeightTextField.getText();
        if(StringUtils.isNotEmpty(impurityWeightStr) && StringUtil.isPositiveNumber(impurityWeightStr))
            weighTemp.setImpurityWeight(Double.parseDouble(impurityWeightStr));

        String netWeightStr = netWeightTextField.getText();
        if(StringUtils.isNotEmpty(netWeightStr) && StringUtil.isPositiveNumber(netWeightStr))
            weighTemp.setNetWeight(Double.parseDouble(netWeightStr));

        EWarehouse warehouse = warehouseComboBox.getValue();
        weighTemp.setWarehouseId(warehouse.getWarehouseId());
        weighTemp.setWarehouseName(warehouse.getWarehouseName());

        WCustomer customer = customerComboBox.getValue();

        EGoods goods = goodsComboBox.getValue();
        weighTemp.setGoodsId(goods.getGoodsId());
        weighTemp.setGoodsName(goods.getGoodsName());

        SysUser chargeMan = chargemanComboBox.getValue();
        if(StringUtils.isNotEmpty(chargeMan.getUserId())) {
            weighTemp.setChargemanId(chargeMan.getUserId());
            weighTemp.setChargemanName(chargeMan.getFullname() == null ? chargeMan.getUsername() : chargeMan.getFullname());
        }

        String priceStr = priceTextField.getText();
        if(StringUtils.isNotEmpty(priceStr) && StringUtil.isPositiveNumber(priceStr))
            weighTemp.setPrice(Double.parseDouble(priceStr));

        String deductionMoneyStr = deductionMoneyTextField.getText();
        if(StringUtils.isNotEmpty(deductionMoneyStr) && StringUtil.isPositiveNumber(deductionMoneyStr))
            weighTemp.setDeductionMoney(Double.parseDouble(deductionMoneyStr));

        String amountStr = amountTextField.getText();
        if(StringUtils.isNotEmpty(amountStr) && StringUtil.isPositiveNumber(amountStr))
            weighTemp.setAmount(Double.parseDouble(amountStr));

        weighTemp.setRemark(remarkTextField.getText());

        WWorkMode wWorkMode = wWorkModeDao.queryById("001");//工作模式
        //获取过磅类别
        WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
        weighTemp.setWeighType(weighTypeBean.getWeighTypeId());

        if(weighTypeBean.getWeighTypeId()<2){//入库 / 出库
            weighTemp.setIsDelivery(isDeliveryComboBox.getValue().isDelivery());
            SysUser salesMan = salesmanComboBox.getValue();
            if(StringUtils.isNotEmpty(salesMan.getUserId())) {
                weighTemp.setSalesmanId(salesMan.getUserId());
                weighTemp.setSalesmanName(salesMan.getFullname() == null ? salesMan.getUsername() : salesMan.getFullname());
            }
        }

        if(weighTypeBean.getWeighTypeId()==2){//内部周转
            EWarehouse warehouse1 = warehouse1ComboBox.getValue();//原仓库
            weighTemp.setWarehouse1Id(warehouse1.getWarehouseId());
            weighTemp.setWarehouse1Name(warehouse1.getWarehouseName());

            EGoods goods1 = goods1ComboBox.getValue();//原物品
            weighTemp.setGoods1Id(goods1.getGoodsId());
            weighTemp.setGoods1Name(goods1.getGoodsName());
        }else if(customer!=null){//不是内部周转
            weighTemp.setCustomerId(customer.getCustomerId());
            weighTemp.setCustomerName(customer.getCustomerName());
            weighTemp.setCustomerPhone(customer.getCustomerPhone());
        }

        WWeighTemp temp = new WWeighTemp();
        temp.setLicensePlate(weighTemp.getLicensePlate());
        temp.setStatus(-1);
        List<WWeighTemp> temps = wWeighTempDao.query(temp);
        Date now = new Date();
        if(temps==null || temps.isEmpty()){//第一次过磅
            weighTemp.setModifyTime(now);
            weighTemp.setCreateTime(now);
            weighTemp.setEnterTime(now);
            weighTemp.setPic1(capturePicDir);
            switch (wWorkMode.getWmodeWeigh()){
                case 0://只需要一次过磅
                    weighTemp.setOutTime(now);
                    weighTemp.setStatus(0);//过磅完成
                    break;
                case 1://需要二次过磅
                    weighTemp.setStatus(-1);//需要二次过磅
                    break;
            }
            wWeighTempDao.insert(weighTemp);
        }else{//数据库中已经存在，表示是第二次过磅
            temp = temps.get(0);
            weighTemp.setWeighId(temp.getWeighId());
            weighTemp.setEnterTime(temp.getEnterTime());
            weighTemp.setPic1(temp.getPic1());
            weighTemp.setModifyTime(now);
            weighTemp.setOutTime(now);
            weighTemp.setPic2(capturePicDir);
            weighTemp.setStatus(0);//过磅完成
            wWeighTempDao.update(weighTemp);
        }

        if(weighTemp.getStatus()==0){//过磅完成上传到服务器
            switch (weighTemp.getWeighType()){
                case 0://入库
                    AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2EBuy(weighTemp, false))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<EBuy>("保存采购记录") {
                            @Override
                            protected void onHandleSuccess(EBuy eBuy) {
                                submitWeighSuccess(weighTemp, eBuy.getBuyId());
                                if(autoPrint) new Thread(new PrintWeighRecordThread(eBuy)).start();//打印
                            }
                        });
                    break;
                case 1://出库
                    AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2ESell(weighTemp, false))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<ESell>("保存销售记录") {
                            @Override
                            protected void onHandleSuccess(ESell eSell) {
                                submitWeighSuccess(weighTemp, eSell.getSellId());
                                if(autoPrint) new Thread(new PrintWeighRecordThread(eSell)).start();//打印
                            }
                        });
                    break;
                case 2://内部周转
                    AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2ETransfer(weighTemp, false))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<ETransfer>("保存内部转库记录") {
                            @Override
                            protected void onHandleSuccess(ETransfer eTransfer) {
                                submitWeighSuccess(weighTemp, eTransfer.getTransferId());
                                if(autoPrint) new Thread(new PrintWeighRecordThread(eTransfer)).start();//打印
                            }
                        });
                    break;
                case 3://其它过磅
                    AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2EOther(weighTemp, false))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<EOther>("保存其它过磅记录") {
                            @Override
                            protected void onHandleSuccess(EOther eOther) {
                                submitWeighSuccess(weighTemp, eOther.getOtherWeighId());
                                if(autoPrint) new Thread(new PrintWeighRecordThread(eOther)).start();//打印
                            }
                        });
                    break;
            }
        }else { //第一次过磅 完成， 保存临时库成功，
            clearForm();//清空表单
            lprCameraThread.finishWeigh();//绿灯放行
            reflushWeighListTableView();//刷新列表
        }
    }

    /**
     * 上传记录成功后，修改本地临时记录，上传图片
     * @param weighId 服务器返回记录的ID，不是本地临时记录的ID
     */
    private void submitWeighSuccess(WWeighTemp weighTemp, String weighId) {
        weighTemp.setStatus(1);//上传记录成功
        weighTemp.setModifyTime(new Date());
        wWeighTempDao.update(weighTemp);
        runLater(()->
            clearForm()//保存成功清空表单
        );
        lprCameraThread.finishWeigh();//绿灯放行
//        runLater(()->reflushWeighListTableView());//刷新列表

        List<File> picFiles = getCapturePicFiles(weighTemp.getPic1(), null);
        picFiles = getCapturePicFiles(weighTemp.getPic2(), picFiles);

        switch (picFiles.size()){
            case 0://没有要上传的图片，删除临时记录
                wWeighTempDao.deleteById(weighTemp.getWeighId());
                runLater(()->reflushWeighListTableView());//刷新列表
                break;
            default:
                uploadPic(weighTemp, picFiles, weighId);
        }
    }

    /**
     * 获取抓拍的图片
     * @param dirPath
     * @param picFiles
     * @return
     */
    private List<File> getCapturePicFiles(String dirPath, List<File> picFiles){
        if(picFiles==null) picFiles = new LinkedList<>();
        if(StringUtils.isNotEmpty(dirPath)){//第二次过磅图片
            logger.debug("将要上传的抓拍图片地址："+dirPath);
            File picDir = new File(dirPath);
            if(picDir.isDirectory() && picDir.listFiles()!=null && Objects.requireNonNull(picDir.listFiles()).length>0) {
                picFiles.addAll(Arrays.asList(Objects.requireNonNull(picDir.listFiles())));
            }
        }
        return picFiles;
    }

    /**
     * 上传图片
     */
    private void uploadPic(WWeighTemp weighTemp, List<File> picFiles, String weighId){
        if(picFiles!=null && !picFiles.isEmpty()){
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)//表单类型
                    .addFormDataPart("weighId", weighId);

            for (int i=0; i<picFiles.size(); i++){
                File pic = picFiles.get(i);
                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), pic);
                builder.addFormDataPart("capturePics", i+"_"+pic.getName(), imageBody);
            }

            List<MultipartBody.Part> parts = builder.build().parts();

            AppRequest.getInstance().getService().uploadCapturePic(parts)
                    .compose(ServiceRxSchedulers.compose())
                    .subscribe(new ServiceSubscriber<>("上传抓拍的图片") {
                        @Override
                        protected void onHandleSuccess(Void aVoid) {
                            logger.debug("上传抓拍图片成功");
                            uploadPicSuccess(weighTemp, picFiles);
                        }
                    });
        }
    }

    /**
     * 上传图片成功后，修改本地临时记录，删除记录与图片
     * @param picFiles
     */
    private void uploadPicSuccess(WWeighTemp weighTemp, List<File> picFiles){
        weighTemp.setStatus(2);//上传图片成功
        weighTemp.setModifyTime(new Date());
        wWeighTempDao.update(weighTemp);
//        runLater(()->reflushWeighListTableView());//刷新列表

        //先删除图片
        for(File pic : picFiles)
            FileUtils.deleteQuietly(pic);

        wWeighTempDao.deleteById(weighTemp.getWeighId());
        runLater(()->reflushWeighListTableView());//刷新列表
    }


    /**
     * 获取重量
     */
    public void getWeigh(){
        WWorkMode wWorkMode = wWorkModeDao.queryById("001");//工作模式
        //读取过磅重量数据
        String weighStr = weighLEDLabel.getText();

        if(StringUtils.isNotEmpty(weighStr) && StringUtil.isPositiveNumber(weighStr)){
            boolean weghfunSuccess = false;
            switch (wWorkMode.getWmodeWeigh()) {
                case 0://一次过磅，
                    weghfunSuccess=weighFun1(weighStr);
                    break;
                case 1://二次过磅
                    weghfunSuccess=weighFun2(weighStr);
                    break;
            }

            if(weghfunSuccess) {
                //摄像头抓拍照片
                capturePicDir = createCapturePicDir();
                if (!cameraThread.capturePic(capturePicDir)) capturePicDir = null;

                if (autoWeigh) submitData();//自动过磅，获取完数据后，自动提交数据
            }
        }
    }

    /**
     *
     * @param weighStr
     */
    private boolean weighFun1(String weighStr){
        boolean weghfunSuccess = false;
        double weigh = Double.parseDouble(weighStr);
        if(weigh>0) {//过磅仪表重量必须大于0
            grossWeightTextField.setText(weighStr);
            tareWeightTextField.setText("0");
            weghfunSuccess = true;
        }
        return weghfunSuccess;
    }

    /**
     *
     * @param weighStr
     */
    private boolean weighFun2(String weighStr){
        boolean weghfunSuccess = true;

        WLicensePlate licensePlate = lprComboBox.getValue();
        if(licensePlate==null || StringUtils.isEmpty(licensePlate.getWlpNumber())) {//车牌为空
            MyAlert.showError("错误","获取重量","请输入车牌号");
//            grossWeightTextField.setText(weighStr);
            weghfunSuccess = false;
        }else {
            WWeighTemp temp = new WWeighTemp();
            temp.setLicensePlate(licensePlate.getWlpNumber());
            temp.setStatus(-1);
            List<WWeighTemp> temps = wWeighTempDao.query(temp);
            Date now = new Date();
            if(temps==null || temps.isEmpty()){//第一次过磅
                double weigh = Double.parseDouble(weighStr);
                if(weigh>0) //过磅仪表重量必须大于0
                    grossWeightTextField.setText(weighStr);
                else
                    weghfunSuccess = false;
            }else {
                temp = temps.get(0);
                double fistWeight = temp.getGrossWeight();//取第一次过磅的重量
                double secoundWeight = Double.parseDouble(weighStr);//和第二次过磅的重量
                if(fistWeight>=secoundWeight){
                    tareWeightTextField.setText(weighStr);
                }else {
                    tareWeightTextField.setText(String.valueOf(fistWeight));
                    grossWeightTextField.setText(weighStr);
                }
            }
        }

        return weghfunSuccess;
    }

    /**
     * 清空表单
     */
    private void clearForm(){
        lprComboBox.setValue(null);//车牌
        grossWeightTextField.setText(null);//毛
        tareWeightTextField.setText(null);//皮
        netWeightTextField.setText(null);//净

        if(!autoWeigh) {//不是自动过磅
//            weighTypeComboBox.getSelectionModel().select(0);//过磅类别
//            warehouseComboBox.getSelectionModel().select(0);//仓库
//            warehouse1ComboBox.getSelectionModel().select(0);//仓库1
            customerComboBox.setValue(null);//客户
//            goodsComboBox.getSelectionModel().select(0);//物品
//            goods1ComboBox.getSelectionModel().select(0);//物品1
            salesmanComboBox.getSelectionModel().select(0);//业务员
            chargemanComboBox.getSelectionModel().select(0);//负责人
//            isDeliveryComboBox.getSelectionModel().select(0);//是否自提
            impurityWeightTextField.setText(null);//扣重
            priceTextField.setText(null);//单价
            deductionMoneyTextField.setText(null);//扣款
            remarkTextField.setText(null);//备注
        }

        if(!autoWeigh || weighTypeComboBox.getValue().getWeighTypeId()!=3){//自动过磅时其它过磅类别过磅费不用清空
            amountTextField.setText(null);//总价
        }
    }

    @Override
    public void close() {
        cameraThread.close();
        weighCommThread.close();
        ctrlCommThread.close();
        lprCameraThread.close();
    }
}
